/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.counter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;

@Service
public class CounterService {

    private final MongoOperations mongoOperations;

    @Autowired
    public CounterService(MongoOperations mongoOperations) {
        this.mongoOperations = mongoOperations;
    }

    public long getNextSequence(String sequenceType) {

        Query query = query(where("id").is(sequenceType));

        if (!mongoOperations.exists(query, Counter.class)) {
            long sequence = 0;
            mongoOperations.insert(new Counter(sequenceType, sequence));
            return sequence;
        }

        Update update = new Update().inc("sequence", 1);

        Counter counter = mongoOperations.findAndModify(query, update, Counter.class);

        return counter.getSequence() + 1;
    }

}
